package com.zengdada.dml.job;

import com.alibaba.fastjson.JSONObject;
import com.zengdada.authority.annotation.JobSysLog;
import com.zengdada.authority.config.listener.jobs.TimedTaskJob;
import com.zengdada.authority.exception.RoutineException;
import com.zengdada.authority.model.TimedTask;
import com.zengdada.authority.utils.ExceptionUtil;
import com.zengdada.dml.model.DmlColumnExtend;
import com.zengdada.dml.model.DmlExtend;
import com.zengdada.dml.model.type.StaticSelect;
import com.zengdada.dml.service.impl.DmlExecutor;
import com.zengdada.dml.service.impl.DmlPlatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019-03-29 13:08
 * @Description:
 */

@Slf4j
@Component
public class ExecuteDmlJob extends TimedTaskJob {

    @Autowired
    DataSource dataSource;

    @Autowired
    DmlPlatService dmlPlatService;

    @Override
    @JobSysLog("定时任务-执行DML")
    public void execute(JobExecutionContext context) throws JobExecutionException {
        super.execute(context);
    }

    @Override
    public void execute(TimedTask timedTask) {
        try {
            DmlExtend dml = dmlPlatService.loadDml(timedTask.getDmlId());
            if (dml == null) throw new RuntimeException(String.format("语句%s不存在", timedTask.getDmlId()));
            if (dml instanceof StaticSelect) throw new RuntimeException("该接口不允许执行此操作");
            List<DmlColumnExtend> columns = dml.getColumns(DmlColumnExtend.IN_PARAM_COLUMN, DmlColumnExtend.INOUT_PARAM_COLUMN);
            if (columns.size() > 0) {
                if (StringUtils.isBlank(timedTask.getDmlParams())) throw new RoutineException("参数数量异常，请重新配置！");
                Map map = JSONObject.parseObject(timedTask.getDmlParams(), Map.class);
                if (columns.size() != map.keySet().size()) throw new RoutineException("参数数量异常，请重新配置！");
                for (int i = 0; i < columns.size(); i++) {
                    DmlColumnExtend column = columns.get(i);
                    if (column.getValue() == null) {
                        Object param = map.get(column.getLabel());
                        if (param == null)
                            throw new RoutineException(String.format("未获取到参数 ：%s，请重新配置！", column.getLabel()));
                        if (column.getDataTypeClass().equals(Date.class)) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                            column.setValue(sdf.parse(String.valueOf(param)));
                        } else if (column.getDataTypeClass().equals(String.class))
                            column.setValue(String.valueOf(param));
                        else
                            column.setValue(JSONObject.parseObject(String.valueOf(param), column.getDataTypeClass()));
                    }
                }
            }
            try (Connection conn = dataSource.getConnection()) {
                DmlExecutor executor = new DmlExecutor(null, conn);
                conn.setAutoCommit(false);
                try {
                    executor.execute(dml);
                    conn.commit();
                } catch (Exception e) {
                    conn.rollback();
                    throw new RoutineException(String.format("保存失败:%s", ExceptionUtil.getRawMessage(e)));
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) log.debug("定时任务-dml执行失败：", e);
            throw new RoutineException(ExceptionUtil.getRawMessage(e));
        }
    }
}
